package com.my.geojson.mybatis.config.jts;

import com.my.geojson.mybatis.config.jts.converter.GenericGeometryConverter;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.locationtech.jts.geom.Geometry;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 〈功能简述〉<br>
 * 〈PGgeometry转org.locationtech.jts.geom.Geometry及其继承类〉
 *
 * @author Mr.QL
 * @ClassName AbstractJtsGeometryTypeHandler
 * @Date 2021-12-10 16:58
 * @Version 1.0
 */
@SuppressWarnings("unchecked")
public abstract class AbstractJtsGeometryTypeHandler<T extends Geometry> extends BaseTypeHandler<T> {
    static final GenericGeometryConverter GEOMETRY_CONVERTER = new GenericGeometryConverter();

    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, GEOMETRY_CONVERTER.to(parameter, ps.getConnection().getMetaData().getDatabaseProductName()));
    }

    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return (T) GEOMETRY_CONVERTER.from(rs.getObject(columnName), rs.getStatement().getConnection().getMetaData().getDatabaseProductName());
    }

    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return (T) GEOMETRY_CONVERTER.from(rs.getObject(columnIndex), rs.getStatement().getConnection().getMetaData().getDatabaseProductName());
    }

    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return (T) GEOMETRY_CONVERTER.from(cs.getObject(columnIndex), cs.getConnection().getMetaData().getDatabaseProductName());
    }

}
